package com.hongyuan.venue.ui.home.view_mode;

import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.reflect.TypeToken;
import com.hongyuan.mvvmhabitx.binding.command.BindingAction;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.venue.base.CustomViewModel;
import com.hongyuan.venue.data.Constants;
import com.hongyuan.venue.data.MyRepository;
import com.hongyuan.venue.data.md5.BaseUtil;
import com.hongyuan.venue.ui.home.activity.UseCouponListActivity;
import com.hongyuan.venue.ui.home.beans.CouponBean;
import com.hongyuan.venue.ui.home.beans.SecheduleBeans;
import com.hongyuan.venue.ui.home.beans.VenuePayBeans;
import com.hongyuan.venue.ui.main.activity.PayActivity;
import com.hongyuan.venue.ui.main.beans.V3SuccessBeans;
import com.hongyuan.venue.utils.BigDecimalUtils;
import com.hongyuan.venue.utils.GsonUtil;
import com.hongyuan.venue.utils.TimeUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class VenuePayViewModel extends CustomViewModel<MyRepository> {

    private Disposable mSubscription;
    public ObservableField<CouponBean.ListBean> couponBean = new ObservableField<>();

    //选中的对象字符串
    public ObservableField<String> allSelect = new ObservableField<>();
    //选中的总费用
    public ObservableField<String> allPrice = new ObservableField<>("0");

    public VenuePayViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //通知显示优惠卷信息
        public SingleLiveEvent<String> showCouponName = new SingleLiveEvent<>();
    }

    //选取优惠券
    public BindingCommand selectCoupon = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("couponFor","2");
            bundle.putString("totalMoney",allPrice.get());
            //bundle.putInt("couponId",couponId);
            bundle.putString("os_id",userToken.getOs_id());
            startActivity(UseCouponListActivity.class,bundle);
        }
    });

    //去支付页面
    public BindingCommand goPay = new BindingCommand(() -> {

        setParams("os_id",userToken.getOs_id())
                .setParams("detail",allSelect.get())
                .requestData(Constants.ORDER_GYM_MX);
    });


    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(CouponBean.ListBean.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(coupon -> {
                    if(coupon != null && BaseUtil.isValue(coupon.getCoupon_money())){
                        uc.showCouponName.setValue(coupon.getCoupon_name());

                        if(couponBean.get() == null || !BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }else{
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }
                        couponBean.set(coupon);

                    }else{
                        if(couponBean.get() != null && BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                        }

                        uc.showCouponName.setValue("");
                        couponBean.set(null);
                    }

                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.ORDER_GYM_MX){

            VenuePayBeans orderBean = (VenuePayBeans)dataBean;

            V3SuccessBeans beans = new V3SuccessBeans();
            beans.setType(V3SuccessBeans.TYPE.BUYCARD);
            beans.setTitleText("订单完成");
            beans.setShowText("购买成功");
            beans.setBtn2Text("完成");
            List<V3SuccessBeans.ItemConten> list = new ArrayList<>();

            List<SecheduleBeans.ListBean> datas =  GsonUtil.getGson().fromJson(allSelect.get(), new TypeToken<List<SecheduleBeans.ListBean>>(){}.getType());
            V3SuccessBeans.ItemConten itemConten = null;
            if(datas != null && datas.size() > 0){
                for(SecheduleBeans.ListBean listBean : datas){
                    itemConten = new V3SuccessBeans.ItemConten();
                    itemConten.setContent(listBean.getArea_name());
                    itemConten.setItemTitle("场地");
                    list.add(itemConten);

                    itemConten = new V3SuccessBeans.ItemConten();
                    itemConten.setContent(TimeUtil.getStringByFormat(listBean.getS_time()*1000,TimeUtil.dateFormatDotYMDHM) +"-"+ TimeUtil.getStringByFormat(listBean.getE_time()*1000,TimeUtil.dateFormatHM));
                    itemConten.setItemTitle("预约时间");
                    list.add(itemConten);

                    itemConten = new V3SuccessBeans.ItemConten();
                    itemConten.setContent("￥"+listBean.getType_price());
                    itemConten.setItemTitle("价格");
                    list.add(itemConten);
                }
            }

            if(couponBean.get() != null){
                itemConten = new V3SuccessBeans.ItemConten();
                itemConten.setContent("-¥"+ BaseUtil.getNoZoon(couponBean.get().getCoupon_money()));
                itemConten.setItemTitle("优惠:");
                list.add(itemConten);
            }
            beans.setItemContens(list);

            Bundle bundle = new Bundle();
            bundle.putString("payPrice",allPrice.get());
            bundle.putString("payOid",orderBean.getO_id());
            bundle.putSerializable("successBeans",beans);
            startActivity(PayActivity.class,bundle);
        }

    }

}
